package com.zmovie.admin.controller.session;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmovie.admin.constant.Constants;
import com.zmovie.admin.controller.vo.SessionVO;
import com.zmovie.common.error.BusinessException;
import com.zmovie.common.error.EnumBusinessError;
import com.zmovie.common.response.CommonReturnType;
import com.zmovie.framework.domain.*;
import com.zmovie.framework.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 挚爱之夕
 * @version 1.0
 * @implSpec 场次管理模块
 * @since 2023-12-03 16:39
 */
@Controller
@RequestMapping("/session/info")
@Api(tags = "场次管理模块")
public class SessionController {
    @Autowired
    private SessionService sessionService;
    @Autowired
    private CinemaService cinemaService;
    @Autowired
    private MovieService movieService;
    @Autowired
    private MovieRuntimeService movieRuntimeService;

    @Autowired
    private HallService hallService;

    @GetMapping
    @ApiOperation("场次管理页面")
    public String index(Model model){
        //查影院
        List<Cinema> cinemas = cinemaService.list();
        model.addAttribute(Constants.CINEMAS_KEY, cinemas);
        //查电影
        List<Movie> movies = movieService.list();
        model.addAttribute(Constants.MOVIES_KEY, movies);
        //播放时段
        List<MovieRuntime> movieRuntimes = movieRuntimeService.list();
        model.addAttribute(Constants.MOVIE_RUNTIMES_KEY, movieRuntimes);
        //分页查询
        Page<Session> sessionPage = sessionService.pageSession(Integer.valueOf(Constants.PAGE_NO), Integer.valueOf(Constants.PAGE_SIZE), new Session());
        model.addAttribute(Constants.SESSION_PAGE, convert(sessionPage));
        return "session/session_info";
    }

    @GetMapping("/{id}")
    @ResponseBody
    @ApiOperation("根据id过去场次信息")
    public Object getSession(@PathVariable("id") Integer id) throws BusinessException {
        if(id == null) throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR);
        return CommonReturnType.success(sessionService.getById(id));
    }

    @DeleteMapping("/{id}")
    @ResponseBody
    @ApiOperation("删除场次")
    public Object deleteSession(@PathVariable("id") Integer id) throws BusinessException {
        if(id == null) throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR);
        sessionService.removeById(id);
        return CommonReturnType.success("删除成功!");
    }
    @PostMapping
    @ResponseBody
    @ApiOperation("添加场次")
    public Object addSession(@Validated Session session){
        //状态(0-禁用，1-启用)
        session.setState(0);
        //座位信息
        Hall hall = hallService.getById(session.getHallId());
        session.setSeats(hall.getSeatState());
        //座位总数
        session.setNums(hall.getSeatNumsRow());
        sessionService.save(session);
        return CommonReturnType.success("添加成功!");
    }

    @PutMapping
    @ResponseBody
    @ApiOperation("修改场次")
    public Object updateSession(@Validated Session session) throws BusinessException {
        if(session.getId() == null){
            throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        sessionService.updateById(session);
        return CommonReturnType.success("修改成功!");
    }

    @DeleteMapping
    @ResponseBody
    @ApiOperation("批量删除")
    public Object deleteSessionBatch(Integer[] id) throws BusinessException {
        if(id == null || id.length == 0){
            throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        sessionService.removeByIds(Arrays.asList(id));
        return CommonReturnType.success("删除成功!");
    }

    @PostMapping("/search")
    @ApiOperation("搜索")
    public String search(Session session, @NotNull Integer pageNo, @NotNull Integer pageSize, Model model){
        Page<Session> sessionPage = sessionService.pageSession(pageNo, pageSize, session);
        model.addAttribute(Constants.SESSION_PAGE, convert(sessionPage));
        return "session/session_info :: sessionList";
    }

    @PostMapping("/loadHall")
    @ApiOperation("根据影院id加载其下影厅")
    public String loadHall(Integer cinemaId, Model model) throws BusinessException {
        if(cinemaId == null){
            throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        List<Hall> halls = hallService.listHallByCinemaId(cinemaId);
        model.addAttribute(Constants.HALLS_KEY, halls);
        return "session/session_info :: hallData";
    }

    @PutMapping("/state")
    @ResponseBody
    @ApiOperation("修改场次状态")
    public Object changeState(Session session) throws BusinessException {
        if(session.getId() == null || session.getState() == null){
            throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        sessionService.updateSession(session);
        return CommonReturnType.success("修改场次状态成功!");
    }

    @PostMapping("/seat")
    @ApiOperation("查看场次座位")
    public  String seatState(@NotNull(message = "场次id不能为空") Integer id,
                             Model model){
        Session session = sessionService.getById(id);
        String seats = session.getSeats();
        List<int[]> seat = JSON.parseArray(seats, int[].class);
        model.addAttribute("row", seat.size());
        model.addAttribute("col", seat.get(0).length);
        model.addAttribute(Constants.SEAT_KEY, seat);
        return "session/session_info :: seatData";
    }

    private SessionVO convert(Session session){
        SessionVO sessionVO = new SessionVO();
        BeanUtils.copyProperties(session, sessionVO);
        //电影院
        Cinema cinema = cinemaService.getById(session.getCinemaId());
        sessionVO.setCinema(cinema);
        //影厅
        Hall hall = hallService.getById(session.getHallId());
        sessionVO.setHall(hall);
        //电影
        Movie movie = movieService.getById(session.getMovieId());
        sessionVO.setMovie(movie);
        //电影播放时段
        MovieRuntime movieRuntime = movieRuntimeService.getById(session.getMovieRuntimeId());
        sessionVO.setMovieRuntime(movieRuntime);
        return sessionVO;
    }
    private Page<SessionVO> convert(Page<Session> sessionPage){
        Page<SessionVO> sessionVOPage = new Page<>();
        BeanUtils.copyProperties(sessionPage, sessionVOPage);
        List<SessionVO> sessionVOList = sessionPage.getRecords().stream().map(this::convert).collect(Collectors.toList());
        sessionVOPage.setRecords(sessionVOList);
        return sessionVOPage;
    }
}
